package SlidingWindow;

/**
 * @ClassName LC1658
 * @Description TODO
 * @Author ZJX
 * @Date 2024/9/20 9:55
 * @Version 1.0
 */
public class LC1658 {
//    正 难 则 反
    public int minOperations(int[] nums, int x) {
        int sum = 0;
        for(int n : nums){
            sum += n;
        }
        if (sum < x){
            return -1;
        }
        int target = sum - x;
        int cur = 0;
        int maxLength = -1;

        for (int right = 0,left = 0; right < nums.length; right++) {
            cur += nums[right];
            while(cur > target && left <= right){
                cur -= nums[left];
                left++;
            }
            if (cur == target){
                maxLength = Math.max(maxLength, right - left + 1);
            }
        }
        return maxLength == -1 ? -1 : nums.length - maxLength;
    }
}
